package org.chengyi.model_shop.service.impl;

import cn.hutool.core.date.DateUtil;
import org.chengyi.model_shop.entity.Cart;
import org.chengyi.model_shop.mapper.CartMapper;
import org.chengyi.model_shop.mapper.ProductMapper;
import org.chengyi.model_shop.service.CartService;
import org.chengyi.model_shop.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private ProductMapper productMapper;

    @Override
    public String addCart(Cart cart) {
        Integer userId = ThreadLocalUtil.get();
        if (userId == null) {
            return "用户未登录";
        }
        Cart existingCart = cartMapper.getCartByUserIdAndProductId(userId, cart.getProductId());
        int quantityChange = cart.getQuantity();
        if (existingCart != null) {
            int newQuantity = existingCart.getQuantity() + quantityChange;
            if (newQuantity <= 0) {
                cartMapper.deleteCart(userId, cart.getProductId());
                return "删除成功";
            } else {
                existingCart.setQuantity(newQuantity);
                existingCart.setUpdatedAt(DateUtil.now());
                cartMapper.updateCart(existingCart);
                return "添加成功";
            }
        } else {
            if (quantityChange <= 0) {
                return "数量必须大于0";
            }
            cart.setUserId(userId);
            cart.setCreatedAt(DateUtil.now());
            cart.setUpdatedAt(DateUtil.now());
            cartMapper.addCart(cart);
            return "添加成功";
        }
    }
    @Override
    public String deleteCart(Integer productId) {
        Integer userId = ThreadLocalUtil.get();
        if (userId == null) {
            return "用户未登录";
        }
        Cart cart = cartMapper.getCartByUserIdAndProductId(userId, productId);
        if (cart != null) {
            // 恢复库存
            productMapper.increaseStock(productId, cart.getQuantity());
        }
        return cartMapper.deleteCart(userId, productId) > 0 ? "删除成功" : "删除失败";
    }

    @Override
    public List<Cart> getCartList() {
        Integer userId = ThreadLocalUtil.get();
        if (userId == null) {
            return null;
        }
        return cartMapper.getCartList(userId);
    }
}
